import axios from 'axios';

// 创建 axios 实例
const service = axios.create({
  // 设置 baseURL
  baseURL: 'http://xsk.com:10086', 
  timeout: 5000 // 请求超时时间
});

service.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});



// 封装 post 请求
const post = async (url, data, errorMessage) => {
    try {
        const response = await service.post(url, data, {
            headers: {
                'Content-Type': 'application/json',
                'accept': '*/*'
            }
        });
        return response.data;
    } catch (error) {
        console.error(errorMessage, error);
        return null;
    }
};



const put = async (url, data, errorMessage) => {
    try {
        const response = await service.put(url,data, {
            headers: {
                'Content-Type': 'application/json',
                'accept': '*/*'
            }
        });
        if (response.ok) {
            this.courseSchedules = await response.json();
        } else {
            throw new Error(`${errorMessage}失败`);
        }
    } catch (error) {
        console.error(`${errorMessage}出错：`, error);
        throw new Error(`${errorMessage}出错`);
    }
};

// 封装 post 请求
const get = async (url, data, errorMessage) => {
    try {
        const response = await service.get(url, data);
        return response.data;
    } catch (error) {
        console.error(`${errorMessage}出错：`, error);
        throw new Error(`${errorMessage}出错`);
    }
};



const delete_ = async (url, data,message) => {
    try {
        const response = await service.delete(url, data,{
            headers: {
                'Content-Type': 'application/json',
                'accept': '*/*'
            }
        });
        return response.data;
    } catch (error) {
        console.error(`${message}出错：`, error);
        throw new Error(`${message}出错`);
    }
};

export default { post,get,put,delete_};